
#include "Shelf.h"


library::Shelf::Shelf(int max, QObject *parent) :
  max(max), QObject(parent) {
    mutex = new QMutex();
  }

void library::Shelf::take(int pos) {
  collection[pos]->lock();
}

void library::Shelf::put(int pos) {
  collection[pos]->unlock();
}

void library::Shelf::put_new(int pos) {
  collection[pos]->unlock();
  emit newBook();
}

int library::Shelf::try_write_new() {

  mutex->lock();

  if(collection.size() >= max) {
    mutex->unlock();
    return -1;
  }

  int idx = collection.size();

  collection.push_back(new QMutex());
  collection[collection.size()-1]->tryLock();
  mutex->unlock();

  return idx;

}

int library::Shelf::size() {
  return collection.size();
}


